package com.atguigu.demo;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author 孔德成
 * @Slogan 致敬大师，致敬未来的你
 * @date 2021/8/10
 */

/**
 * 10 个线程写，10个线程读
 */
public class ReentrantReadWriteLockDemo1 {
    public static void main(String[] args) {
        MyCache myCache = new MyCache();
        for (int i = 1; i <= 10; i++) {
            int finalI = i;
            new Thread(() -> {
                myCache.write(finalI, finalI);
            }, "w" + i).start();
        }

        for (int i = 1; i <= 10; i++) {
            int finalI = i;
            new Thread(() -> {
                myCache.read(finalI);
            }, "r" + i).start();
        }
    }
}

/**
 * 缓存资源类
 */
class MyCache {
    final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
    Map<Integer, Integer> map = new HashMap<>();

    public void write(Integer key, Integer value) {
        rwl.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "\t----开始写");
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + "\t----结束写");
        } finally {
            rwl.writeLock().unlock();
        }

    }

    public void read(Integer key) {
        rwl.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "\t----开始读");
            Integer v = map.get(key);
            System.out.println(Thread.currentThread().getName() + "\t----结束读：" + v);
        } finally {
            rwl.readLock().unlock();
        }
    }
}
